<template>
  <view class="food-edit-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">{{ isEditMode ? '编辑菜品' : '新增菜品' }}</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 基本信息 -->
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="item-label"><text class="required">*</text> 菜品名称</text>
          <input 
            class="item-input" 
            v-model="formData.name" 
            placeholder="请输入菜品名称"
            maxlength="50"
          />
        </view>

        <view class="form-item">
          <text class="item-label"><text class="required">*</text> 菜品分类</text>
          <picker 
            mode="selector" 
            :range="categories" 
            range-key="name"
            :value="categoryIndex"
            @change="onCategoryChange"
          >
            <view class="picker-view">
              {{ selectedCategoryName || '请选择分类' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="item-label">菜品描述</text>
          <textarea 
            class="item-textarea" 
            v-model="formData.description" 
            placeholder="请输入菜品描述"
            maxlength="200"
          />
        </view>
      </view>

      <!-- 价格设置 -->
      <view class="form-section">
        <text class="section-title">价格设置</text>
        
        <view class="form-item">
          <text class="item-label"><text class="required">*</text> 现价（元）</text>
          <input 
            class="item-input" 
            type="digit"
            v-model="formData.price" 
            placeholder="请输入现价"
          />
        </view>

        <view class="form-item">
          <text class="item-label">原价（元）</text>
          <input 
            class="item-input" 
            type="digit"
            v-model="formData.originalPrice" 
            placeholder="请输入原价（可选）"
          />
        </view>
      </view>

      <!-- 库存管理 -->
      <view class="form-section">
        <text class="section-title">库存管理</text>
        
        <view class="form-item">
          <text class="item-label"><text class="required">*</text> 库存数量</text>
          <input 
            class="item-input" 
            type="number"
            v-model="formData.stock" 
            placeholder="请输入库存数量"
          />
        </view>
      </view>

      <!-- 菜品图片 -->
      <view class="form-section">
        <text class="section-title">菜品图片</text>
        
        <!-- 图片上传区域 -->
        <view class="upload-section">
          <view class="upload-area" @click="chooseImage" v-if="!formData.image">
            <text class="upload-icon">📷</text>
            <text class="upload-text">点击上传图片</text>
            <text class="upload-hint">支持jpg、png、gif，最大5MB</text>
          </view>
          
          <!-- 图片预览 -->
          <view class="image-preview" v-if="formData.image">
            <image :src="formData.image" mode="aspectFill" class="preview-img" />
            <view class="image-actions">
              <button class="action-btn reupload-btn" @click="chooseImage">
                <text>🔄 重新上传</text>
              </button>
              <button class="action-btn delete-btn" @click="deleteImage">
                <text>🗑️ 删除图片</text>
              </button>
            </view>
          </view>
          
          <!-- 上传进度 -->
          <view class="upload-progress" v-if="uploadProgress > 0 && uploadProgress < 100">
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: uploadProgress + '%' }"></view>
            </view>
            <text class="progress-text">上传中：{{ uploadProgress }}%</text>
          </view>
        </view>
      </view>

      <!-- 菜品标签 -->
      <view class="form-section">
        <text class="section-title">菜品标签</text>
        
        <view class="switch-item">
          <text class="switch-label">是否爆款</text>
          <switch 
            :checked="formData.isHot === 1" 
            @change="onHotChange"
            color="#ff8a00"
          />
        </view>

        <view class="switch-item">
          <text class="switch-label">是否推荐</text>
          <switch 
            :checked="formData.isRecommended === 1" 
            @change="onRecommendChange"
            color="#ff8a00"
          />
        </view>

        <view class="form-item">
          <text class="item-label">标签</text>
          <view class="tag-checkboxes">
            <label 
              class="checkbox-item" 
              v-for="tag in availableTags" 
              :key="tag"
            >
              <checkbox 
                :value="tag" 
                :checked="selectedTags.includes(tag)"
                @click="toggleTag(tag)"
              />
              <text class="checkbox-label">{{ tag }}</text>
            </label>
          </view>
        </view>
      </view>

      <!-- 辣度选项 -->
      <view class="form-section">
        <text class="section-title">辣度选项</text>
        
        <view class="tag-checkboxes">
          <label 
            class="checkbox-item" 
            v-for="level in availableSpiceLevels" 
            :key="level"
          >
            <checkbox 
              :value="level" 
              :checked="selectedSpiceLevels.includes(level)"
              @click="toggleSpiceLevel(level)"
            />
            <text class="checkbox-label">{{ level }}</text>
          </label>
        </view>
      </view>

      <!-- 菜品状态 -->
      <view class="form-section">
        <text class="section-title">菜品状态</text>
        
        <view class="switch-item">
          <view class="switch-info">
            <text class="switch-label">上架状态</text>
            <text class="switch-desc">关闭后用户将无法看到此菜品</text>
          </view>
          <switch 
            :checked="formData.status === 1" 
            @change="onStatusChange"
            color="#ff8a00"
          />
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="action-buttons">
      <button class="save-btn" @click="handleSave">{{ isEditMode ? '保存修改' : '添加菜品' }}</button>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import merchantService from '../../../services/merchant.js'
import categoryService from '../../../services/category.js'
import { smartBack } from '../../../utils/navigation.js'
import CustomModal from '../../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      isEditMode: false,
      foodId: null,
      
      // 分类数据
      categories: [],
      categoryIndex: 0,
      
      // 表单数据
      formData: {
        name: '',
        categoryId: null,
        description: '',
        image: '',
        price: '',
        originalPrice: '',
        stock: '',
        isHot: 0,
        isRecommended: 0,
        tags: [],
        spiceLevels: [],
        status: 1
      },
      
      // 可选标签
      availableTags: ['新鲜', '热门', '麻辣', '清淡', '经典', '健康', '高蛋白'],
      selectedTags: [],
      
      // 可选辣度
      availableSpiceLevels: ['不辣', '微辣', '中辣', '重辣', '特辣'],
      selectedSpiceLevels: [],
      
      // 图片上传
      uploadProgress: 0  // 上传进度
    }
  },
  computed: {
    selectedCategoryName() {
      if (this.categories.length > 0 && this.categoryIndex >= 0) {
        return this.categories[this.categoryIndex].name
      }
      return ''
    }
  },
  onLoad(options) {
    this.getStatusBarHeight()
    
    // 判断是新增还是编辑
    if (options.mode === 'edit' && options.id) {
      this.isEditMode = true
      this.foodId = options.id
    } else {
      this.isEditMode = false
    }
    
    // 加载分类和数据
    this.loadCategories()
    
    if (this.isEditMode) {
      this.loadFoodDetail()
    }
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },

    // 加载分类列表
    async loadCategories() {
      try {
        const response = await categoryService.getCategories()
        this.categories = response.data || response || []
        
        // 如果有分类且没有选中，默认选中第一个
        if (this.categories.length > 0 && !this.formData.categoryId) {
          this.categoryIndex = 0
          this.formData.categoryId = this.categories[0].id
        }
      } catch (error) {
        console.error('加载分类失败:', error)
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        })
      }
    },

    // 加载菜品详情（编辑模式）
    async loadFoodDetail() {
      if (!this.foodId) return
      
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await merchantService.getFoodDetail(this.foodId)
        const food = response.data || response
        
        console.log('菜品详情:', food)
        
        // 填充表单
        this.formData = {
          name: food.name || '',
          categoryId: food.categoryId || food.category_id,
          description: food.description || '',
          image: food.image || '',
          price: String(food.price || ''),
          originalPrice: String(food.originalPrice || food.original_price || ''),
          stock: String(food.stock || ''),
          isHot: food.isHot !== undefined ? food.isHot : (food.is_hot || 0),
          isRecommended: food.isRecommended !== undefined ? food.isRecommended : (food.is_recommended || 0),
          tags: food.tags || [],
          spiceLevels: food.spiceLevels || food.spice_levels || [],
          status: food.status !== undefined ? food.status : 1
        }
        
        // 设置已选标签
        this.selectedTags = Array.isArray(this.formData.tags) ? [...this.formData.tags] : []
        this.selectedSpiceLevels = Array.isArray(this.formData.spiceLevels) ? [...this.formData.spiceLevels] : []
        
        // 设置分类索引
        if (this.formData.categoryId && this.categories.length > 0) {
          const index = this.categories.findIndex(cat => cat.id === this.formData.categoryId)
          if (index >= 0) {
            this.categoryIndex = index
          }
        }
        
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('加载菜品详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 分类选择变化
    onCategoryChange(e) {
      this.categoryIndex = e.detail.value
      this.formData.categoryId = this.categories[this.categoryIndex].id
    },

    // 爆款开关
    onHotChange(e) {
      this.formData.isHot = e.detail.value ? 1 : 0
    },

    // 推荐开关
    onRecommendChange(e) {
      this.formData.isRecommended = e.detail.value ? 1 : 0
    },

    // 状态开关
    onStatusChange(e) {
      this.formData.status = e.detail.value ? 1 : 0
    },

    // 切换标签
    toggleTag(tag) {
      setTimeout(() => {
        const index = this.selectedTags.indexOf(tag)
        if (index > -1) {
          this.selectedTags.splice(index, 1)
        } else {
          this.selectedTags.push(tag)
        }
        this.formData.tags = [...this.selectedTags]
      }, 100)
    },

    // 切换辣度
    toggleSpiceLevel(level) {
      setTimeout(() => {
        const index = this.selectedSpiceLevels.indexOf(level)
        if (index > -1) {
          this.selectedSpiceLevels.splice(index, 1)
        } else {
          this.selectedSpiceLevels.push(level)
        }
        this.formData.spiceLevels = [...this.selectedSpiceLevels]
      }, 100)
    },

    // 表单验证
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入菜品名称',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.categoryId) {
        uni.showToast({
          title: '请选择分类',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.price || parseFloat(this.formData.price) <= 0) {
        uni.showToast({
          title: '请输入正确的价格',
          icon: 'none'
        })
        return false
      }

      if (this.formData.originalPrice && parseFloat(this.formData.originalPrice) < parseFloat(this.formData.price)) {
        uni.showToast({
          title: '原价不能低于现价',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.stock || parseInt(this.formData.stock) < 0) {
        uni.showToast({
          title: '请输入正确的库存',
          icon: 'none'
        })
        return false
      }

      return true
    },

    // 保存菜品
    async handleSave() {
      if (!this.validateForm()) {
        return
      }

      try {
        uni.showLoading({ title: '保存中...' })

        // 准备提交数据
        const submitData = {
          categoryId: this.formData.categoryId,
          name: this.formData.name,
          description: this.formData.description,
          image: this.formData.image,
          price: parseFloat(this.formData.price),
          originalPrice: this.formData.originalPrice ? parseFloat(this.formData.originalPrice) : null,
          stock: parseInt(this.formData.stock),
          isHot: this.formData.isHot,
          isRecommended: this.formData.isRecommended,
          tags: this.selectedTags,
          spiceLevels: this.selectedSpiceLevels,
          status: this.formData.status
        }

        console.log('📤 提交的商品数据:', submitData)
        console.log('📷 图片URL:', this.formData.image)

        if (this.isEditMode) {
          // 编辑模式
          await merchantService.updateFood(this.foodId, submitData)
        } else {
          // 新增模式
          await merchantService.addFood(submitData)
        }

        uni.hideLoading()
        uni.showToast({
          title: this.isEditMode ? '保存成功' : '添加成功',
          icon: 'success'
        })

        // 返回上一页
        setTimeout(() => {
          smartBack('/pages/merchant/foods/foods')
        }, 1000)

      } catch (error) {
        uni.hideLoading()
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      }
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,  // 只允许选择1张图片
        sizeType: ['compressed'],  // 压缩图
        sourceType: ['album', 'camera'],  // 相册或相机
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          console.log('选择的图片路径:', tempFilePath)
          
          // 上传图片
          this.uploadImage(tempFilePath)
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 上传图片到服务器
    uploadImage(filePath) {
      // 获取token（注意：token的key是 jwt_token，不是 token）
      const token = uni.getStorageSync('jwt_token')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      // 重置上传进度
      this.uploadProgress = 0
      
      // 上传文件
      const uploadTask = uni.uploadFile({
        url: 'http://localhost:8080/api/v1/upload/image',  // 后端上传接口
        filePath: filePath,
        name: 'file',  // 后端接收的参数名
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (uploadRes) => {
          console.log('上传响应:', uploadRes)
          
          if (uploadRes.statusCode === 200) {
            try {
              const result = JSON.parse(uploadRes.data)
              console.log('解析后的结果:', result)
              
              if (result.code === 200 && result.data && result.data.url) {
                // 上传成功，保存图片URL
                this.formData.image = result.data.url
                this.uploadProgress = 100
                
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
                
                // 1秒后清除进度条
                setTimeout(() => {
                  this.uploadProgress = 0
                }, 1000)
              } else {
                throw new Error(result.message || '上传失败')
              }
            } catch (error) {
              console.error('解析响应失败:', error)
              uni.showToast({
                title: '上传失败：' + error.message,
                icon: 'none'
              })
              this.uploadProgress = 0
            }
          } else {
            uni.showToast({
              title: '上传失败：' + uploadRes.statusCode,
              icon: 'none'
            })
            this.uploadProgress = 0
          }
        },
        fail: (error) => {
          console.error('上传失败:', error)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          this.uploadProgress = 0
        }
      })
      
      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        this.uploadProgress = res.progress
        console.log('上传进度:', res.progress + '%')
      })
    },
    
    // 删除图片
    deleteImage() {
      this.$refs.customModal.show({
        type: 'warning',
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        confirmText: '确认删除',
        cancelText: '取消',
        onConfirm: () => {
          this.formData.image = ''
          uni.showToast({
            title: '已删除',
            icon: 'success'
          })
        }
      })
    },

    // 返回
    goBack() {
      smartBack('/pages/merchant/foods/foods')
    }
  }
}
</script>

<style lang="scss" scoped>
.food-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 180rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  z-index: 998;
}

.nav-left {
  position: absolute;
  left: 0;
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

// 表单内容
.form-content {
  margin-top: calc(var(--status-bar-height) + 88rpx + 20rpx);
  padding: 20rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

// 表单项
.form-item {
  margin-bottom: 32rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-label {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.required {
  color: #ff6b6b;
  margin-right: 4rpx;
}

.item-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e1e5e9;
  border-radius: 12rpx;
  font-size: 26rpx;
}

.item-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border: 2rpx solid #e1e5e9;
  border-radius: 12rpx;
  font-size: 26rpx;
  line-height: 1.6;
}

.picker-view {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e1e5e9;
  border-radius: 12rpx;
  font-size: 26rpx;
  line-height: 72rpx;
  color: #333;
}

// 图片上传区域
.upload-section {
  margin-top: 20rpx;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  border: 2rpx dashed #ddd;
  border-radius: 16rpx;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    background: #f0f0f0;
    transform: scale(0.98);
  }
}

.upload-icon {
  font-size: 80rpx;
  margin-bottom: 16rpx;
}

.upload-text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.upload-hint {
  font-size: 22rpx;
  color: #999;
}

// 图片预览
.image-preview {
  position: relative;
  width: 100%;
  height: 400rpx;
  border-radius: 16rpx;
  overflow: hidden;
  background: #f5f5f5;
}

.preview-img {
  width: 100%;
  height: 100%;
}

// 图片操作按钮
.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 2rpx;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10rpx);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  font-size: 24rpx;
  color: #fff;
  background: transparent;
  
  &.reupload-btn {
    background: rgba(255, 138, 0, 0.8);
    
    &:active {
      background: rgba(255, 138, 0, 1);
    }
  }
  
  &.delete-btn {
    background: rgba(255, 59, 48, 0.8);
    
    &:active {
      background: rgba(255, 59, 48, 1);
    }
  }
}

// 上传进度
.upload-progress {
  margin-top: 20rpx;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #ff8a00, #ffb300);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-text {
  display: block;
  text-align: center;
  font-size: 22rpx;
  color: #ff8a00;
  margin-top: 8rpx;
}

// 开关项
.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.switch-info {
  flex: 1;
}

.switch-label {
  display: block;
  font-size: 26rpx;
  color: #333;
}

.switch-desc {
  display: block;
  font-size: 22rpx;
  color: #999;
  margin-top: 8rpx;
}

// 标签选择
.tag-checkboxes {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 12rpx 20rpx;
  background: #f5f5f5;
  border-radius: 20rpx;
}

.checkbox-label {
  font-size: 24rpx;
  color: #333;
  margin-left: 8rpx;
}

// 保存按钮
.action-buttons {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
}
</style>
